﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Web.Profile;
using System.IO;
using System.Text.RegularExpressions;
using System.Net;
using System.Drawing;
using PMG.model;
using PMG.data;
using PMG.data.Tool;
using Spring.Context;
using Spring.Context.Support;

/// <summary>
/// BasePage SoCool页面的基类
/// </summary>
public class AdminPage : System.Web.UI.Page
{
    public AdminPage() { }

    #region 管理员
    /// <summary>
    /// 当前管理员帐号
    /// </summary>
    public USER CurrAdmin
    {
        get
        {
            // 检查SESSION
            if (Session["adminUser"] != null)
                return (USER)Session["adminUser"];
            else
            {
                // 检查COOKIES
                // 帐号和过期时间
                if (Request.Cookies["adminId"] != null)
                {
                    int adminId = 0;
                    try
                    {
                        adminId = Convert.ToInt32(Request.Cookies["adminId"].Value);
                    }
                    catch { return null; }

                    // 获取
                    IApplicationContext ic = new XmlApplicationContext
                        (ParameterFactory.CfgFilePath
                        , ParameterFactory.CfgBusinessFilePath);
                    DaoUserSpring dao = (DaoUserSpring)ic.GetObject("DaoUserSpring");
                    USER admin = dao.LoadFromId(adminId);
                    if (admin != null)
                    {
                        Session["adminUser"] = admin;
                        return admin;
                    }
                    else
                        return null;
                }
                else
                    return null;
            }
        }
    }
    /// <summary>
    /// 登录用户，存储其项ID
    /// SESSION，COOKIE
    /// </summary>
    /// <param name="dtoUser"></param>
    /// <param name="remember">记住登录？</param>
    public void Loggin(USER admin, bool remember)
    {
        // 存入SESSION
        Session["adminUser"] = admin;
        if (remember)
        {
            // 存入COOKIE
            HttpCookie cookieAdminId = new HttpCookie("adminId", admin.Id.ToString());
            cookieAdminId.HttpOnly = true;
            cookieAdminId.Expires = DateTime.Now.AddDays(7);
            Response.Cookies.Add(cookieAdminId);
        }
    }
    /// <summary>
    /// 注销用户，退出登录
    /// </summary>
    public void Logout()
    {
        if (Session["adminUser"] != null)
            Session["adminUser"] = null;
        // 删除COOKIE
        HttpCookie cookie = Response.Cookies["adminId"];
        cookie.HttpOnly = true;
        if (cookie != null)
        {
            cookie.Expires = DateTime.Now.AddDays(-1);
            Response.Cookies.Add(cookie);
        }
    }
    #endregion

    #region 执行一段客户端脚本
    /// <summary>
    /// 执行一段客户端的SCRIPT
    /// 形如<script>xxxx</script>
    /// </summary>
    /// <param name="str"></param>
    public void RunScript(string sScript)
    {
        // 客户端脚本管理
        ClientScriptManager csm = Page.ClientScript;
        string csName = "cscript";
        Type csType = this.GetType();
        if (!csm.IsClientScriptBlockRegistered(csType, csName))
        {
            csm.RegisterClientScriptBlock(this.GetType(), "cscript", sScript);
        }
    }
    #endregion

    #region 辅助方法——Alert对话框、获取参数、文本断行

    /// <summary>
    /// 弹出对话框提示。
    /// </summary>
    /// <param name="str"></param>
    public void MsgBox(String str)
    {
        StringBuilder sb = new StringBuilder(str);
        sb.Replace(@"\", @"\\"); //	\  -->	\\
        sb.Replace(@"""", @"\"""); //	"  --> \"
        sb.Replace(@"'", @"\'"); //	'  --> \'
        sb.Replace("\r\n", "\\r\\n");
        sb.Replace("\r", "\\r");
        sb.Replace("\n", "\\n");
        String sScript;
        sScript = "<script>alert(" + "' " + sb.ToString() + " ' " + " );";
        sScript = sScript + "</script> ";

        // 客户端脚本管理
        ClientScriptManager csm = Page.ClientScript;
        string csName = "notpass";
        Type csType = this.GetType();
        if (!csm.IsClientScriptBlockRegistered(csType, csName))
        {
            csm.RegisterClientScriptBlock(this.GetType(), "notpass", sScript);
        }
        //this.Page.RegisterStartupScript("notpass", sScript);
    }

    #endregion

    #region 获取客户端真实IP
    /// <summary>
    /// 获取IP,有待完善
    /// </summary>
    public string ClientIP
    {
        get
        {
            string userip = "";
            // 如果客户端用了代理服务器，则应该用ServerVariables("HTTP_X_FORWARDED_FOR")方法
            if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
                userip = Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
            // 如果客户端没用代理，应该用Request.ServerVariables("REMOTE_ADDR")方法
            if (userip.Length == 0)
                userip = Request.ServerVariables["REMOTE_ADDR"].ToString();
            return userip;
        }
    }
    #endregion

    #region 判断一个元素是否在一个数组内
    /// <summary>
    /// 判断一个元素
    /// 是否在数组内
    /// </summary>
    /// <param name="element">欲比较元素</param>
    /// <param name="Arrays">数组</param>
    /// <returns></returns>
    public bool isElementInArray(object element, object[] Arrays)
    {
        // 先反射类型，如果不同，失败
        if (!element.GetType().Equals(Arrays.GetType().GetElementType()))
            return false;

        // 进行比较，是否存在
        for (int i = 0; i < Arrays.Length; i++)
        {
            if (element.ToString().ToLower().Equals(Arrays[i].ToString().ToLower()))
                return true;
        }

        // 未存在元素
        return false;
    }
    #endregion

    #region 字符串截取
    /// <summary>
    /// 字符串截取，取前N个，多余的用指定字串表示
    /// </summary>
    /// <param name="orignalString">原字串</param>
    /// <param name="length">取的长度</param>
    /// <param name="chopedString">多出来的表示字串</param>
    /// <returns>截取的字符串</returns>    
    public static String Chop(String orignalString, int length, String chopedString)
    {
        // 判断
        if (orignalString == null || orignalString.Length == 0)
        {
            return orignalString;
        }
        // 如果已经小于等于
        if (orignalString.Length <= length)
        {
            return orignalString;
        }
        // 返回结果
        string returnStr = orignalString.Replace("</a>", "");
        // 去除链接
        string pattern = @"<a\shref=.*?>";
        // 正则比较
        Regex reg = new Regex(pattern, RegexOptions.IgnoreCase
            | RegexOptions.CultureInvariant
            | RegexOptions.IgnorePatternWhitespace
            | RegexOptions.Compiled);
        // 结果集
        MatchCollection mclist = reg.Matches(orignalString);

        if (mclist != null && mclist.Count > 0)
        {
            foreach (Match mc in mclist)
            {
                returnStr = returnStr.Replace(mc.Value, "");
            }
        }

        if (returnStr.Length > length)
            return returnStr.Substring(0, length) + chopedString;
        else
            return returnStr;
    }
    #endregion

    #region 提交成功，转向
    /// <summary>
    /// 转向其他页面
    /// 带提示信息；    
    /// </summary>
    public void GotoPageAndAlert(string pageUrl, string message)
    {
        // 拼串，带返回地址：
        string gotoStr = pageUrl;

        StringBuilder sb = new StringBuilder(gotoStr);
        sb.Replace(@"\", @"\\"); //	\  -->	\\
        sb.Replace(@"""", @"\"""); //	"  --> \"
        sb.Replace(@"'", @"\'"); //	'  --> \'
        sb.Replace("\r\n", "\\r\\n");
        sb.Replace("\r", "\\r");
        sb.Replace("\n", "\\n");
        String sScript;
        sScript = "<script>alert('" + message + "');";
        sScript = sScript + "location.href=\"" + sb.ToString() + "\"";
        sScript = sScript + "</script> ";
        this.Page.RegisterStartupScript("notpass", sScript);
    }
    #endregion

    #region 输出为静态页
    /// <summary>
    /// 输出静态页
    /// </summary>
    #region bool OutputStaticHtml(string url,string path,string filename)
    public bool OutputStaticHtml(string url, string path, string filename)
    {
        Encoding code = Response.ContentEncoding;
        StreamReader sr = null;
        StreamWriter sw = null;
        string str = null;

        //读取远程路径
        WebRequest temp = WebRequest.Create(url);
        WebResponse myTemp = temp.GetResponse();
        sr = new StreamReader(myTemp.GetResponseStream(), code);
        //读取
        try
        {
            sr = new StreamReader(myTemp.GetResponseStream(), code);
            str = sr.ReadToEnd();
        }
        catch (Exception ex)
        {
            throw ex;
            return false;
        }
        finally
        {
            sr.Close();
        }

        // 正则替换CSS路径
        #region 正则替换CSS路径

        string pattern = "href=\"../App_Themes/";
        string target = string.Format("href=\"{0}App_Themes/",
                         ConfigurationManager.AppSettings["domain"]);
        ReplaceRegular(ref str, pattern, target);
        pattern = @"<form\sname=.*?>";
        target = string.Empty;
        ReplaceRegular(ref str, pattern, target);
        pattern = "</form>";
        ReplaceRegular(ref str, pattern, target);

        #endregion

        //写入
        #region 写入
        try
        {
            sw = new StreamWriter(Path.Combine(path, filename), false, code);
            sw.Write(str);
            sw.Flush();
            return true;
        }
        catch (Exception ex)
        {
            throw ex;
            return false;
        }
        finally
        {
            sw.Close();
        }
        #endregion
    }
    #endregion

    /// <summary>
    /// 正则替换
    /// </summary>
    /// <param name="str">正文</param>
    /// <param name="regular">表达式</param>
    /// <param name="target">目标</param>
    #region void ReplaceRegular(ref string str,string pattern,string target)
    private void ReplaceRegular(ref string str, string pattern, string target)
    {
        // 正则比较
        Regex reg = new Regex(pattern, RegexOptions.IgnoreCase
            | RegexOptions.CultureInvariant
            | RegexOptions.IgnorePatternWhitespace
            | RegexOptions.Compiled);
        // 结果集
        MatchCollection mclist = reg.Matches(str);
        if (mclist != null && mclist.Count > 0)
        {
            foreach (Match mc in mclist)
            {
                // 替换为绝对路径引用
                str = str.Replace(mc.Value, target);
            }
        }
    }
    #endregion

    #endregion

    #region 读取静态内容
    /// <summary>
    /// 读取文件内容并显示
    /// </summary>
    /// <param name="HtmlFile"></param>
    public void ReadStaticHtml(string HtmlFile)
    {
        FileStream fs = new FileStream(HtmlFile, FileMode.Open, FileAccess.Read
                    , FileShare.ReadWrite, 0x1000, false);
        byte[] bBuffer = new byte[0x1000];
        int nRealRead = 0;
        do
        {
            nRealRead = fs.Read(bBuffer, 0, 0x1000);
            //Response.BinaryWrite(bBuffer);
            Response.Write(Encoding.UTF8.GetString(bBuffer, 0, nRealRead));
        } while (nRealRead == 0x1000);
        Response.Flush();
        Response.End();
        fs.Close();
        fs.Dispose();
    }

    #endregion

    #region 水印

    /// <summary>
    /// 加文件水印
    /// 生成文件为 源文件名_mark.扩展名
    /// </summary>
    /// <param name="width">限定输出宽度</param>
    /// <param name="height">高</param>
    #region string MakeTextMark(string imgPath,string text,int fontsize,int width,int height)
    public string MakeTextMark(string imgPath, string text, int fontsize, int width, int height)
    {
        //上传文件
        string extension = Path.GetExtension(imgPath);
        string path = Path.GetDirectoryName(imgPath);
        string filename = Path.Combine(path,
            Path.GetFileName(imgPath).Split(new char[] { '.' })[0] + "_mark" + extension);
        // 文字水印
        // destimage用于限定大小        
        System.Drawing.Image image = System.Drawing.Image.FromFile(imgPath);
        // 尺寸比较
        if (width > image.Width)
        {
            width = image.Width;
        }
        if (height > image.Height)
        {
            height = image.Height;
        }

        System.Drawing.Image destimage = new Bitmap(width, height);
        Graphics g = Graphics.FromImage(destimage);

        // 目标区域
        RectangleF destRect = new RectangleF(0F, 0F, (float)width, (float)height);
        // 源区域
        RectangleF srcRect = new RectangleF(0F, 0F, (float)image.Width, (float)image.Height);

        g.DrawImage(image, destRect, srcRect, GraphicsUnit.Pixel);
        // 字体大小
        Font f = new Font("Verdana", fontsize);
        Brush b = new SolidBrush(Color.White);
        // 打印位置
        g.DrawString(text, f, b,
            width - text.Length * fontsize * 2, height - fontsize * 2);

        // 保存文件
        destimage.Save(filename);
        destimage.Dispose();
        image.Dispose();
        g.Dispose();

        return filename;
    }
    #endregion

    /// <summary>
    /// 加图片水印
    /// </summary>
    #region string MakePicMark(string imgPath,string markFile)
    public string MakePicMark(string imgPath, string markFile)
    {
        // 加水印后文件
        string extension = Path.GetExtension(imgPath);
        string path = Path.GetFullPath(imgPath);
        string filename = path
            + Path.GetFileName(imgPath).Split(new char[] { '.' })[0] + "_mark" + extension;
        // 加水印
        System.Drawing.Image image = System.Drawing.Image.FromFile(imgPath);
        System.Drawing.Image copyImage = System.Drawing.Image.FromFile(markFile);
        Graphics g = Graphics.FromImage(image);
        g.DrawImage(copyImage, new Rectangle(image.Width - copyImage.Width, image.Height - copyImage.Height, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel);
        g.Dispose();
        // 保存文件
        image.Save(filename);
        image.Dispose();

        return filename;
    }
    #endregion

    /// <summary>
    /// 根据图片的绝对全路径得到URL
    /// </summary>
    /// <param name="fullpath">全路径</param>
    /// <param name="appSetting">URL前缀</param>
    #region string getImgUrl(string fullpath, string urlPrefix)
    public string getImgUrl(string fullpath, string urlPrefix)
    {
        string[] str = fullpath.Split(new char[] { '\\' });
        string filename = str[str.Length - 1];
        return urlPrefix + "/" + filename;
    }
    #endregion

    #endregion

    #region 防刷新重复提交

    /*
		 * 调用方法：
		 *	假设页面上有一个隐藏的TextBox，名称为txtToken，或者ViewState。
		 *	则
		 *		（1）在Page_Load事件完毕之后，调用 txtToken.Text = GetToken();
		 *		（2）在处理提交的事件中，
		 *			try
		 *			{
		 *				if (ValidateToken(txtToken.Text))	//验证通过才进行处理
		 *				{
		 *					//实际的处理……
		 *				}
		 *				else
		 *				{
		 *					//可以加一些提示……
		 *				}
		 *			}
		 *			finally
		 *			{
		 *				txtToken.Text = GetToken();		//确保产生新的Token
		 *			}
		 * 
		 */

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        if (!IsPostBack)
        {
            ViewState["txtToken"] = GetToken();
        }
    }

    /// <summary>
    /// 调用此方法产生一个新的Token，并保存到Session中。
    /// 然后调用方应该将得到的Token同时保存到页面的隐藏字段中。
    /// </summary>
    /// <returns></returns>

    public string GetToken()
    {
        string token = Guid.NewGuid().ToString();
        Session["token"] = token;
        return token;
    }

    public string GetToken4Upload()
    {
        string token = Guid.NewGuid().ToString();
        Session["token2"] = token;
        return token;
    }

    public string GetToken3()
    {
        string token = Guid.NewGuid().ToString();
        Session["token3"] = token;
        return token;
    }

    /// <summary>
    /// 调用方应该从页面的隐藏字段中取出保存的Token，
    /// 调用此方法判断得到的Token是否与Session中的一致。
    /// 若不一致，则表示重复提交。
    /// </summary>
    /// <param name="token"></param>
    /// <returns></returns>
    public bool ValidateToken(string token)
    {
        string savedToken = Session["token"] as String;
        if (savedToken == null)
        {
            return true; //若Session已失效，则默认通过
        }
        return String.Equals(token, savedToken);
    }

    public bool ValidateToken2(string token)
    {
        string savedToken = Session["token2"] as String;
        if (savedToken == null)
        {
            return true; //若Session已失效，则默认通过
        }
        return String.Equals(token, savedToken);
    }

    public bool ValidateToken3(string token)
    {
        string savedToken = Session["token3"] as String;
        if (savedToken == null)
        {
            return true; //若Session已失效，则默认通过
        }
        return String.Equals(token, savedToken);
    }
  
    #endregion

    #region 获取页数
    public int GetPageCount(int recordCount, int pageSize)
    {
        int pagecount = recordCount / pageSize;
        // 余数
        int yushu = recordCount % pageSize;
        if (yushu > 0)
            pagecount += 1;
        return pagecount;
    }
    #endregion

    #region 错误处理
    public void ErrorHandle() { Response.Redirect("/Admin/Default.aspx"); }
    #endregion

    #region 获取UTF8编码
    public string GetUtf8(string str)
    {
        byte[] btCN = System.Text.Encoding.Default.GetBytes(str);
        string strUTF8 = System.Text.Encoding.UTF8.GetString(btCN);
        return strUTF8;
    }
    #endregion

    #region 检测QueryString，非法则停止响应
    public void CheckQueryString(string queryList)
    {
        string[] qs = queryList.Split(',');
        bool flag = true;		//合法
        foreach (string str in Request.QueryString.AllKeys)
        {
            for (int i = 0; i < qs.Length; i++)
            {
                if (qs[i].Equals(str))
                    break;
                if (i == qs.Length - 1 && !qs[i].Equals(str))
                    flag = false;
            }
            if (!flag)
                break;
        }
        if (!flag)
        {
            Response.Clear();
            Response.Write("非法GET参数");
            Response.End();
        }
    }
    #endregion
}
